﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CAGFIP.DataAccess;
using System.Windows.Forms;
using CAGFIP.Utils;

namespace CAGFIP.Edicao
{
    public class ControladorRanking
    {
        #region Singleton

        private static ControladorRanking instance;

        private ControladorRanking() { }

        public static ControladorRanking Instance
        {
            get { return instance ?? (instance = new ControladorRanking()); }
        }

        #endregion

        #region Properties

        public static IRankingDAO RankingDAO
        {
            get
            {
                if (Constants.IsDebug)
                    return RankingDAODebug.Instance;
                else
                    return CAGFIP.Edicao.RankingDAO.Instance;
            }
        }

        #endregion

        #region Methods
        
        public void OnCadastro(double pontuacao, string dificuldade, string nome)
        {
            List<Ranking> rankingList = RankingDAO.VisualizarRanking();
            List<Ranking> rankingListAtualizar = new List<Ranking>();

            int posicao = Constants.PosicoesRanking;

            foreach (Ranking ranking in rankingList)
            {
                if (dificuldade.ToString().Equals(ranking.Dificuldade, StringComparison.OrdinalIgnoreCase))
                {
                    if (pontuacao > ranking.Pontuacao)
                    {
                        if (posicao > ranking.Posicao)
                        {
                            posicao = ranking.Posicao;
                        }
                        ranking.Posicao++;
                        if (ranking.Posicao < Constants.PosicoesRanking)
                        {
                            rankingListAtualizar.Add(ranking);
                        }
                    }
                }
            }
            Ranking novoRanking = new Ranking(dificuldade.ToString(), posicao, nome, pontuacao);
            rankingListAtualizar.Add(novoRanking);

            foreach (Ranking ranking in rankingListAtualizar)
            {
                RankingDAO.AtualizarRanking(ranking);
            }
        }

        public void OnVisualizacao(DataGridView rankingView)
        {
            rankingView.DataSource = RankingDAO.VisualizarRankingDataSet();
        }

        #endregion
    }
}
